import React, { useState, useEffect } from 'react';
import { Button, Space, Tag, message, Select, Spin } from 'antd';
import { PlusOutlined, ArrowLeftOutlined, BookOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { FilterCard, TableCard } from '@/components/common';
import { QuestionBank, QuestionListItem, QuestionType, DifficultyLevel } from '@/types/question';
import { questionService } from '@/services/questionService';

const { Option } = Select;

const QuestionBankDetail: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(false);
  const [bankLoading, setBankLoading] = useState(false);
  const [bank, setBank] = useState<QuestionBank | null>(null);
  const [questions, setQuestions] = useState<QuestionListItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [typeFilter, setTypeFilter] = useState<QuestionType | undefined>();
  const [difficultyFilter, setDifficultyFilter] = useState<DifficultyLevel | undefined>();

  // 加载题库信息
  const fetchBank = async () => {
    if (!id) return;
    setBankLoading(true);
    try {
      const response = await questionService.getQuestionBank(Number(id));
      setBank(response.data.data);
    } catch (error) {
      message.error('获取题库信息失败');
    } finally {
      setBankLoading(false);
    }
  };

  // 加载题目列表
  const fetchQuestions = async (page = 1) => {
    if (!id) return;
    setLoading(true);
    try {
      const response = await questionService.getQuestionBankQuestions(
        Number(id),
        {
          type: typeFilter,
          difficulty: difficultyFilter,
          page,
          limit: pagination.pageSize,
        }
      );
      const data = response.data.data;
      setQuestions(data.results);
      setPagination({
        ...pagination,
        current: page,
        total: data.count,
      });
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBank();
  }, [id]);

  useEffect(() => {
    fetchQuestions(1);
  }, [id, typeFilter, difficultyFilter]);

  // 题型映射
  const questionTypeMap: Record<string, string> = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    composite: '综合题',
  };

  // 难度映射
  const difficultyMap: Record<number, { text: string; color: string }> = {
    1: { text: '非常简单', color: 'green' },
    2: { text: '简单', color: 'blue' },
    3: { text: '中等', color: 'orange' },
    4: { text: '困难', color: 'red' },
    5: { text: '非常困难', color: 'purple' },
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '题目',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text: string, record: QuestionListItem) => (
        <a onClick={() => navigate(`/admin/question/edit/${record.id}`)}>
          {text || '(无标题)'}
        </a>
      ),
    },
    {
      title: '题型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color="cyan">{questionTypeMap[type] || type}</Tag>
      ),
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 100,
      render: (difficulty: number) => {
        const config = difficultyMap[difficulty] || { text: '未知', color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 200,
      render: (tags: string[]) => (
        <>
          {tags?.map((tag, idx) => (
            <Tag key={idx} style={{ marginBottom: 4 }}>{tag}</Tag>
          ))}
        </>
      ),
    },
    {
      title: '使用次数',
      dataIndex: 'use_count',
      key: 'use_count',
      width: 100,
    },
    {
      title: '正确率',
      dataIndex: 'correct_rate',
      key: 'correct_rate',
      width: 100,
      render: (rate: number) => `${(rate * 100).toFixed(1)}%`,
    },
  ];

  if (bankLoading) {
    return <Spin tip="加载中..." />;
  }

  return (
    <div>
      <FilterCard
        pageTitle={
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/admin/question/banks')}>
              返回
            </Button>
            <span>{bank?.name || '题库详情'}</span>
          </Space>
        }
        titleIcon={<BookOutlined />}
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate(`/admin/question/create?bank_id=${id}`)}>
            添加题目
          </Button>
        }
      >
        <Space size="large">
          <span>题目总数：<Tag color="blue">{bank?.question_count || 0}</Tag></span>
          
          <Select
            placeholder="题型筛选"
            style={{ width: 150 }}
            allowClear
            onChange={setTypeFilter}
          >
            <Option value="single_choice">单选题</Option>
            <Option value="multiple_choice">多选题</Option>
            <Option value="true_false">判断题</Option>
            <Option value="fill_blank">填空题</Option>
            <Option value="composite">综合题</Option>
          </Select>

          <Select
            placeholder="难度筛选"
            style={{ width: 150 }}
            allowClear
            onChange={setDifficultyFilter}
          >
            <Option value={1}>非常简单</Option>
            <Option value={2}>简单</Option>
            <Option value={3}>中等</Option>
            <Option value={4}>困难</Option>
            <Option value={5}>非常困难</Option>
          </Select>
        </Space>
      </FilterCard>

      <TableCard
        tableProps={{
          columns,
          dataSource: questions,
          rowKey: 'id',
          loading,
          pagination: {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: (page) => {
              setPagination({ ...pagination, current: page });
              fetchQuestions(page);
            },
          },
        }}
      />
    </div>
  );
};

export default QuestionBankDetail;

